// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Npgsql;

namespace SnapObjects.Data.PostgreSql
{
    internal class PostgreSqlAdoDbCommand : AdoDbCommand
    {
        public PostgreSqlAdoDbCommand(
            [NotNull] string sqlText,
            IEnumerable<IAdoDbParameter> parameters,
            bool addExceptionToTransaction,
            CommandType commandType = CommandType.Text)
            : base(sqlText, parameters, addExceptionToTransaction, commandType)
        {
        }

        protected override string BuildNoExecCommandText(DataContext context, string commandText)
        {
            return $"explain {commandText}";
        }

        protected override void CreateParameters(DataContext dataContext, IDbCommand command)
        {
            if (this.Parameters == null)
            {
                return;
            }

            var typeMapper = dataContext.AdoDbSqlProvider.TypeMapper;

            foreach (var parameter in this.Parameters)
            {
                if (typeof(IEnumerable).IsAssignableFrom(parameter.ClrType)
                     && parameter.ClrType != typeof(string)
                     && parameter.ClrType != typeof(byte[])
                     && this.IsInOperatorParam(parameter.ParameterName, command.CommandText))
                {
                    this.CreateArrayParameter(
                        command, typeMapper, parameter, (IEnumerable)parameter.Value);
                }
                else
                {
                    var typeMapping = !String.IsNullOrWhiteSpace(parameter.TypeName)
                        ? typeMapper.FindMapping(parameter.TypeName)
                        : typeMapper.FindMapping(parameter.ClrType);

                    if (typeMapping != null)
                    {
                        AdoDbParameterBuilder.AddDbParameter((DbCommand)command, typeMapping, parameter);
                    }
                    else
                    {
                        AdoDbParameterBuilder.AddDbParameter((DbCommand)command, parameter);
                    }
                }
            }
        }

        private bool IsInOperatorParam(string paramName, string commandText)
        {
            var pattern = $"[\\s]+[i|I][n|N][\\s]*\\([\\s]*{paramName}[\\s]*\\)";

            var regex = new Regex(pattern);
            
            return regex.IsMatch(commandText);
        }

        public override int ExecuteNonQuery(DataContext dataContext)
        {
            var ret = base.ExecuteNonQuery(dataContext);

            return ret == -1 ? 0 : ret;
        }

        public async override Task<int> ExecuteNonQueryAsync(
            DataContext dataContext, CancellationToken cancellationToken = default)
        {
            var returnParamter = this.Parameters
                  .Where(m => m.Direction == ParameterDirection.ReturnValue)
                  .FirstOrDefault();

            if (returnParamter != null)
            {
                var value = await base.ExecuteScalarAsync(dataContext, cancellationToken);

                ((AdoDbParameter)returnParamter).Value = value;

                return 0;
            }
            else
            {
                var ret = await base.ExecuteNonQueryAsync(dataContext, cancellationToken);

                return ret == -1 ? 0 : ret;
            }
        }

        protected override object Execute(
            DataContext dataContext,
            AdoDbCommandMethod executeMethod,
            CommandBehavior commandBehavior = CommandBehavior.Default)
        {
            if (executeMethod != AdoDbCommandMethod.ExecuteNonQuery)
            {
                return base.Execute(dataContext, executeMethod, commandBehavior);
            }

            var returnParamter = this.Parameters
                .Where(m => m.Direction == ParameterDirection.ReturnValue)
                .FirstOrDefault();

            if (returnParamter != null)
            {
                executeMethod = AdoDbCommandMethod.ExecuteScalar;
            }

            var result = base.Execute(dataContext, executeMethod, commandBehavior);

            if (returnParamter != null)
            {
                ((AdoDbParameter)returnParamter).Value = result;

                result = 0;
            }

            return result;
        }

        protected override int GetSqlDbCode(Exception innerException)
        {
            if (innerException is NpgsqlException ex)
            {
                return ex.ErrorCode;
            }

            return -1;
        }
    }
}
